package com.template.application;

import androidx.appcompat.app.AppCompatActivity;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.RemoteException;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.template.service.TemplateAidlInterface;
import com.template.service.TemplateServiceCallBack;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    private static final String TAG = "TemplateApp";
    private Intent startIntent = null;
    private Button btn_start_service;
    private Button btn_stop_service;
    private Button btn_bind_service;
    private Button btn_unbind_service;
    private Button btn_sync_data;
    private EditText et_data;
    private TextView tv_out;
    private TemplateServiceConn mTemplateServiceConn;
    private TemplateAidlInterface mTemplateService = null;
    private TemplateAppCallBack mTemplateCallBack = null;
    private boolean mConnected = false;
    private static final String TEMPLATE_CLIENT = "TemplateApp1";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initStartIntent();
        setOnClick();
        mTemplateServiceConn = new TemplateServiceConn();
        mTemplateCallBack = new TemplateAppCallBack();
    }

    class TemplateAppCallBack extends TemplateServiceCallBack.Stub {

        @Override
        public void onDataChanged(String data) throws RemoteException {
            Log.d(TAG, "onDataChanged");
            Message msg = new Message();
            Bundle bundle = new Bundle();
            bundle.putString("data", data);
            msg.setData(bundle);
            //发送通知
            handler.sendMessage(msg);
        }
    }
    @Override
    protected void onResume() {
        super.onResume();
        Log.i(TAG, "onResume: ");
    }

    @Override
    protected void onPause() {
        super.onPause();
        Log.i(TAG, "onPause");
    }

    @Override
    protected void onStop() {
        Log.i(TAG, "onStop");
        super.onStop();
    }

    @Override
    protected void onStart() {
        Log.i(TAG, "onStart");
        super.onStart();
    }

    @Override
    protected void onDestroy() {
        Log.i(TAG, "onDestroy");
        super.onDestroy();
        unBindService();
    }

    Handler handler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            //在handler中更新UI
            tv_out.setText(msg.getData().getString("data"));
        };
    };

    private void initStartIntent() {
        startIntent = new Intent ();
        ComponentName componentName = new ComponentName("com.template.service", "com.template.service.TemplateService");
        startIntent.setComponent(componentName);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_start_service:
                //用intent启动Service并传值
                startIntent.putExtra("data", et_data.getText().toString());
                startService(startIntent);
                break;
            case R.id.btn_stop_service:
                //停止Service
                stopService(startIntent);
                break;
            case R.id.btn_bind_service:
                //绑定Service
                bindService(startIntent, mTemplateServiceConn, Context.BIND_AUTO_CREATE);
                break;
            case R.id.btn_unbind_service:
                //解绑Service
                unBindService();
                break;
            case R.id.btn_sync_data:
                //注意：需要先绑定，才能同步数据
                if (mTemplateService != null) {
                    try {
                        mTemplateService.setData(et_data.getText().toString());
                    } catch (RemoteException e) {
                        e.printStackTrace();
                    }
                }
                break;
            default:
                break;
        }
    }

    private void unBindService() {
        if (mTemplateService != null) {
            try {
                mTemplateService.unRegisterCallback(TEMPLATE_CLIENT, (TemplateServiceCallBack)mTemplateCallBack);
            } catch (RemoteException e) {
                e.printStackTrace();
            }
            unbindService(mTemplateServiceConn);
        }
        mTemplateService = null;
        mConnected = false;
    }

    class TemplateServiceConn implements ServiceConnection {
        // 服务被绑定成功之后执行
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            // IBinder service为onBind方法返回的Service实例
            Log.i(TAG, "onServiceConnected: " + mTemplateCallBack);
            mTemplateService = TemplateAidlInterface.Stub.asInterface(service);
            try {

                mTemplateService.registerCallback(TEMPLATE_CLIENT, (TemplateServiceCallBack) mTemplateCallBack);
            } catch (RemoteException e) {
                Log.e(TAG, "RemoteException: " + e);
                e.printStackTrace();
            }
            mConnected = true;
        }

        // 服务奔溃或者被杀掉执行
        @Override
        public void onServiceDisconnected(ComponentName name) {
            Log.i(TAG, "onServiceDisconnected: " + mTemplateCallBack);
            try {
                mTemplateService.unRegisterCallback(TEMPLATE_CLIENT, (TemplateServiceCallBack)mTemplateCallBack);
            } catch (RemoteException e) {
                e.printStackTrace();
            }
            mTemplateService = null;
            mConnected = false;
        }
    }

    private void loadUI() {
        btn_start_service = (Button) findViewById(R.id.btn_start_service);
        btn_stop_service = (Button) findViewById(R.id.btn_stop_service);
        btn_bind_service = (Button) findViewById(R.id.btn_bind_service);
        btn_unbind_service = (Button) findViewById(R.id.btn_unbind_service);
        btn_sync_data = (Button) findViewById(R.id.btn_sync_data);
        et_data = (EditText) findViewById(R.id.et_data);
        tv_out = (TextView) findViewById(R.id.tv_out);
    }

    private void setOnClick() {
        loadUI();
        btn_start_service.setOnClickListener(this);
        btn_stop_service.setOnClickListener(this);
        btn_bind_service.setOnClickListener(this);
        btn_unbind_service.setOnClickListener(this);
        btn_sync_data.setOnClickListener(this);
    }
}